<?php
    /**
     * jQuery helper
     * 
     * @package Helpers
	 * @author Anton Perkin
	 * @version 1.0
	 * 
     */
    class jQueryHelper
    {
        
        /* PUBLIC METHODS */
        
        /**
         * Initilizes the component
         */
        static function Initialize()
        {
            //jQuery files
            HtmlHelper::JavaScript("/./".SYSTEM_HELPERS.'resources/jquery-1.4.4.min');
            HtmlHelper::JavaScript("/./".SYSTEM_HELPERS.'resources/jquery-ui-1.8.7.custom.min');
            HtmlHelper::JavaScript("/./".SYSTEM_HELPERS.'resources/timepicker');
            HtmlHelper::Css("/./".SYSTEM_HELPERS.'resources/jquery-ui-1.8.7.custom');
        }

        /**
         * Generates Accordion
         * 
         * @param string $id accordion id
         * @param array $elements accordion elements
         * @param array $settings accordion settings
         */
        public static function Accordion($id, array $elements, array $settings = array())
        {
            echo self::GenerateFunction('accordion', $id, $settings);
            
            //accordion elements
            echo "<div id='{$id}'>";
            foreach ($elements as $header => $content)
            {
                echo "
                    <h3 style = 'text-align: left'><a href='#'>$header</a></h3>
                    <div>$content</div>                
                ";
            }
            echo "</div>";
        }

        /**
         * Generates Tabs
         * 
         * @param string $id tabs id
         * @param array $elements tabs elements
         * @param array $settings tabs settings
         */
        public static function Tabs($id, array $elements, array $settings = array())
        {
            echo self::GenerateFunction('tabs', $id, $settings);
            
            //accordion elements
            echo "<div id='{$id}'>";
            
            //tabs headers
            $i = 0;
            echo "<ul>";
            foreach ($elements as $header => $content)
            {
                echo "<li><a href='#{$id}-$i'>$header</a></li>";
                $i++;
            }
            echo "</ul>";

            //tabs content
            $j = 0;
            foreach ($elements as $header => $content)
            {
                echo "<div id = '{$id}-$j'>$content</div>";
                $j++;
            }
            
            echo "</div>";
        }        
        
        /**
         * Generates Tabs bar (tabs only, no content)
         * 
         * @param string $id tabs id
         * @param array $elements tabs buttons
         * @param array $settings tabs settings
         */
        public static function TabsBar($id, array $elements, array $settings = array())
        {
            //tabs
            echo "<div id='{$id}' class = 'ui-tabs' style = 'padding: 0px; '><ul class = 'ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header'>";
            foreach ($elements as $key => $tab)
            {
                $active_class = ($tab['active']) ? 'ui-tabs-selected ui-state-active' : '';
                
                echo "<li class = 'ui-state-default ui-corner-top $active_class' onmouseover = '$(this).addClass(\"ui-state-hover\")' onmouseout = '$(this).removeClass(\"ui-state-hover\")'><a href='{$tab['url']}'>{$tab['text']}</a></li>";
            }
            echo "</ul></div>";
        }        
        
        /**
         * Makes the element Resizable
         *
         * @param string $id element id
         * @param array $settings elelemt settings
         */
        public static function Resizable($id, array $settings = array())
        {
            echo self::GenerateFunction('resizable', $id, $settings);
        }        

        /**
         * Adds date picker to the specified element
         * 
         * @param string $id element id
         * @param array $settings element settings
         */
        public static function DatePicker($id, array $settings = array())
        {
            echo self::GenerateFunction('datepicker', $id, $settings);
        }        

        /**
         * Adds datetime picker to the specified element
         * @link http://addyosmani.com/blog/the-missing-date-time-selector-for-jquery-ui/
         * 
         * @param string $id element id
         * @param array $settings element settings
         */
        public static function DateTimePicker($id, array $settings = array())
        {
        	$settings['showTime'] = 'true';
        	$settings['time24h'] = (!isset($settings['time24h'])) ? 'true' : $settings['time24h'];
        	
            echo self::GenerateFunction('datepicker', $id, $settings);
        }        
        
        /**
         * Generates Toolbar
         * 
         * @param string $id toolbar id
         * @param array $elements toolbar elements. Element structure: [text, url, image, attributes]
         * @param array $settings element settings
         */
        public static function Toolbar($id, array $buttons, array $settings = array())
        {
            //create buttons
            self::Button("$id a");

            //style enhancement
            echo "<style>.ui-button-text  {padding: 0.3em 1em !important;}</style>";
            
            //toolbar
            echo "<div id = '$id' class = 'ui-widget-header ui-corner-all' style = 'margin: 1px 0px; width: 100%; '>";
            foreach ($buttons as $key => $button)
            {
                //defaults
                $button['url'] = (isset($button['url'])) ? $button['url'] : '#';
                $buttonImageCss = (isset($button['image'])) ? "background-image: url(".$button['image']."); background-position: 3px 1px; background-repeat: no-repeat; padding: 0px 0px 0px 15px; " : '';
                $button['attributes'] = (isset($button['attributes'])) ? $button['attributes'] : '';
                
                //toolbar button
                echo '
                    <a style = "'.$buttonImageCss.'white-space:nowrap;" 
                       href = "'.$button['url'].'" '.$button['attributes'].'>'.$button['text'].'</a>
                ';
            }
            echo "</div>";
        }        
        
        /**
         * Makes the element a button
         * 
         * @param string $id button id
         * @param array $settings element settings
         */
        public static function Button($id, array $settings = array())
        {
            echo self::GenerateFunction('button', $id, $settings);            
        }       
        
        /**
         * Makes the element a dialog box
         * 
         * @param string $id element id
         * @param array $settings element settings
         * @param string $text if set a div element with popup text is generated
         */
        public static function Dialog($id, array $settings = array(), $text = '')
        {
            echo self::GenerateFunction('dialog', $id, $settings);
            echo (!empty($text)) ? HtmlHelper::Div($text, null, array('id' => $id, 'style' => 'display: none; ')) : '';
        }        
        
        /**
         * Adds autocomplete functionality to the input field
         * TODO: $data extended functionality
         * 
         * @param string $id element id
         * @param array $data array with the prompt data
         * @param array $settings element settings
         */
        public static function AutoComplete($id, $data = array(), array $settings = array())
        {
        	echo "
        		<script>
        			var autocomplete_$id = [";
        		
		        	if (!empty($data))
		        	{
			        	foreach ($data as $unit)
			        	{
			        		$units .= "'$unit',";
			        	}
			        	echo substr($units, 0, strlen($units) - 1);
		           	}
        	
        	echo "	]
        		</script>";
        	
        	$settings['source'] = "autocomplete_$id";
        	
        	echo self::GenerateFunction('autocomplete', $id, $settings);            
        }        
        
        
        /* AJAX */
        
        /**
         * Loads remote data into an XMLHttpRequest object. If you need to send GET/POST requests - use GET()/POST() functions
         *
         * @param array $settings AJAX settings
         * @return string
         */
        public static function Ajax($settings)
        {
        	$result = "$.ajax({".self::GenerateAttributesString($settings)."});";
        	
        	return $result;
        }
        
        /**
         * Submits data via GET
         *
         * @param string $url The URL (address) of data to be loaded
         * @param array|string $data Key/value pairs of data to send to the server or form id
         * @param string $callbackFunction Function to be executed when data is loaded
         * @param string $dataType The type of data expected from the server (html,xml,json,jasonp,script,text).
         * @return string
         */
        public static function Get($url, $data = '', $callbackFunction = '', $dataType = '')
        {
        	//data to submit
			$dataString = self::GetAjaxData($data);
			$dataString = (!empty($dataString)) ? $dataString : "''";
			$callbackFunction = (!empty($callbackFunction)) ? $callbackFunction : "''";
			
        	$result = "$.get('$url', $dataString, $callbackFunction, '$dataType');";
        	
        	return $result;
        }
                
        /**
         * Submits data via POST
         *
         * @param string $url The URL (address) of data to be loaded
         * @param array|string $data Key/value pairs of data to send to the server or form id
         * @param string $callbackFunction Function to be executed when data is loaded
         * @param string $dataType The type of data expected from the server (html,xml,json,jasonp,script,text).
         * @return string
         */
        public static function Post($url, $data = '', $callbackFunction = "''", $dataType = '')
        {
        	//data to submit
			$dataString = self::GetAjaxData($data);
        	
        	$result = "$.post('$url', $dataString, $callbackFunction, '$dataType');";
        	
        	return $result;
        }
        
        /**
         * Loads remote data into selected element(-s)
         *
         * @param string $id placeholder id
         * @param string $url The URL (address) of data to be loaded
         * @param array $data Key/value pairs of data to send to the server
         * @param string $callbackFunction Function to be executed when data is loaded
         */
        public static function Load($id, $url, array $data = array(), $callbackFunction = "''")
        {
        	//data
			$dataString = self::GetAjaxData($data);

            $result = "
                <script type='text/javascript'>
                	$(function() {
                		$('#{$id}').load('$url', $dataString, $callbackFunction);
                	});
                </script>
			";	

            echo $result;
        }
        
        
        /* PRIVATE METHODS */
        
        /**
         * Generates attributes string
         * 
         * @param array $attributes jQuery attributes
         */
        private static function GenerateAttributesString(array $attributes = array())
        {
            $attributes_string = '';
            foreach ($attributes as $name=>$value)
            {
                $attributes_string .= "$name:$value,";
            }
            return substr_replace($attributes_string, '', strrpos($attributes_string, ','), 1);
        }
        
        /**
         * Generates jQuery function
         * 
         * @param string $name function name
         * @param string $id element id
         * @param array $attributes attributes
         */
        private static function GenerateFunction($name, $id, array $attributes = array())
        {
            $result = "
                <script type='text/javascript'>
                	$(function() {
                		$('#{$id}').$name({".self::GenerateAttributesString($attributes)."});
                	});
                </script>
			";

            return $result;
        }
        
        /**
         * Gets AJAX (POST, GET) data parameter
         *
         * @param array|string $data data array or form id
         * @return string
         */
        private static function GetAjaxData($data)
        {
        	$dataString = '';
            if (is_array($data))
        	{
        		if (!empty($data))
        		{
        			$dataString .= '{';
        			foreach ($data as $key => $value)
		        	{
		        		$dataString .= $key.": '".$value."',";
		         	}
		         	$dataString = substr($dataString, 0, strlen($dataString)-1);
        			$dataString .= '}';
        		}
        		else 
        		{
        			$dataString = '{}';
        		}
        	}
        	else 
        	{
        		$dataString = (!empty($dataString)) ? "$('#$data').serialize()" : '';
        	}

        	return $dataString;
        }
    }
    
?>